#ifndef __TIMER_H_
#define __TIMER_H_
/************************************************
 *    Timer
 *      |
 *      |
 *  TimerManager
 *      |
 *      |-getNextTime : 返回离最近需要执行的定时器任务 时间
 *      |
 *      |-listExpireCb(std::vector<std::function<void()>>& cbs): 返回到期的任务
 * 
 * refenrece:
 * Linux下定时器的设计与实现 http://www.ilovecpp.com/2019/01/16/timer/
 * C++ 仿函数和适配器 https://www.cnblogs.com/faithfu/p/8932375.html
*************************************************/
#include "thread.h"
#include "util.h"
#include "log.h"

#include <functional>
#include <memory>
#include <set>
#include <vector>

namespace learnco{

class TimerManger;
class Timer : public std::enable_shared_from_this<Timer> {
friend class TimerManger;

public:
    typedef std::shared_ptr<Timer> ptr;
    Timer(uint64_t ms, std::function<void()>cb, bool recurring , TimerManger* manager);

public:
    uint64_t getNextTime() const {return m_next;}

private:
    uint64_t m_ms = 0;          //执行周期
    uint64_t m_next = 0;        //执行时间 curtime + m_ms
    std::function<void()> m_cb = nullptr;
    TimerManger* m_manager = nullptr;
    bool m_recurring = false;

private:
    struct Comparator{
        bool operator()(const Timer::ptr& lhs, const Timer::ptr& rhs) const;
    };
    
};


// Timer 定时器任务管理 std::set 红黑树 平衡树 查找删除效率O(lgN)
class TimerManger{
friend class Timer;

typedef RWMutex RWMutexType;

public:
    TimerManger(){};
    virtual ~TimerManger(){};

public:
    Timer::ptr addTimer(uint64_t ms, std::function<void()>cb, bool recurring = false);
    uint64_t getNextTime();
    void listExpiredCb(std::vector<std::function<void()> >& cbs);

private:
    std::set<Timer::ptr, Timer::Comparator> m_timers;

private:
    RWMutexType m_mutex;
    bool m_tickled = false;  //防止重复多次唤醒(tickled)

protected:
    virtual void v_onTimerInsertedAtFront() {};

};


}





#endif